import logging
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.const import CONF_HOST
from homeassistant.components.switch import SwitchEntity
from .coordinator import MyCoordinator
from . import DOMAIN
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.core import callback


_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, config, async_add_entities):
    _LOGGER.info("async_setup_platform sensor oilprice")
    coordinator: MyCoordinator = hass.data[DOMAIN][config.entry_id]["coordinator"]
    await coordinator.async_config_entry_first_refresh()
    async_add_entities(
        [
            QBittorrentSwitch(
                name=sensor_name,
                host=config.data[CONF_HOST],
                coordinator=coordinator,
            )
            for sensor_name in coordinator.sensors
        ]
    )


class QBittorrentSwitch(SwitchEntity, CoordinatorEntity):
    _attr_has_entity_name = True

    def __init__(self, name: str, host: str, coordinator: MyCoordinator):
        self.coordinator_name = DOMAIN + "_" + host
        super().__init__(coordinator, context=self.coordinator_name)
        self._unique_did = host + "_" + name
        self._attr_unique_id = self._unique_did
        self._attr_name = name

        self._state = self.coordinator.sensors[name]

    @property
    def device_info(self) -> DeviceInfo:
        """Return the device info."""
        return DeviceInfo(
            identifiers={(DOMAIN, self.coordinator_name)},
            name=self.coordinator_name,
            manufacturer="@YY",
            model=DOMAIN,
            sw_version="0.0.1",
        )

    @callback
    def _handle_coordinator_update(self) -> None:
        """Handle updated data from the coordinator."""
        self._state = self.coordinator.sensors[self._attr_name]
        self.async_write_ha_state()

    @property
    def state(self):
        if self._state:
            return "on"
        else:
            return "off"

    async def async_turn_on(self, **kwargs) -> None:
        await self.toggle()

    async def async_turn_off(self, **kwargs) -> None:
        await self.toggle()

    async def toggle(self):
        if await self.coordinator.toggle_speed_limits_mode():
            self._state = await self.coordinator.async_request_refresh()
